<?php

namespace App\Http\Controllers\Operation;

use App\Classes\Image\UploadImage;
use App\Http\Controllers\Controller;
use App\Http\Requests\Operation\TopbarRequest;
use App\Models\Operation\Topbar;
use App\Repositories\Operation\TopbarRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class TopbarController extends Controller
{
    use ModelForm;

    /** @var  TopbarRepository */
    private $topbarRepository;

    public function __construct(TopbarRepository $topbarRepo)
    {
        $this->topbarRepository = $topbarRepo;
    }

    /**
     * Display a listing of the Topbar.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.topbars.index_header'));
            $content->description(__('operation.topbars.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Topbar.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.topbars.create_header'));
            $content->description(__('operation.topbars.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Topbar in storage.
     *
     * @param TopbarRequest $request
     *
     * @return Response
     */
    public function store(TopbarRequest $request)
    {
        $input                     = $request->all();
        $topbarData                = [];
        $topbarData['name']        = $input['name'];
        $topbarData['title']       = $input['title'];
        $topbarData['description'] = $input['description'];
        $topbarData['css']         = $input['css'];
        $image                     = $request->file('ui'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.topbar');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $topbarData['ui'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $topbar     = $this->topbarRepository->create($topbarData);
        $topbarArea = $input['topbararea'];
        // topbar模板保存成功
        $topbarId = $topbar->id;
        $datas    = [];
        foreach ($topbarArea as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['topbar_id'] = $topbarId;
                $data['layout']    = $value['layout'];
                $data['component'] = $value['component'];
                $data['onfocus']   = $value['onfocus'];
                $data['onclick']   = $value['onclick'];
                $data['editable']  = $value['editable'];
                $datas[]           = $data;
            }
        }
        $insertStatus = DB::table('topbar_areas')->insert($datas);
        if (empty($insertStatus)) {
            Flash::error('topbar模板区位数据插入失败');
            return redirect(route('operation.topbars.index'));
        }
        Flash::success(__('operation.topbars.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.topbars.index'));

    }

    /**
     * Display the specified Topbar.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $topbar = $this->topbarRepository->findWithoutFail($id);

        if (empty($topbar)) {
            Flash::error(__('operation.topbars.not_found'));

            return redirect(route('operation.topbars.index'));
        }

        return view('operation.topbars.show')->with('topbar', $topbar);

    }

    /**
     * Show the form for editing the specified Topbar.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('operation.topbars.edit_header'));
            $content->description(__('operation.topbars.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Topbar in storage.
     *
     * @param  int              $id
     * @param TopbarRequest $request
     *
     * @return Response
     */
    public function update($id, TopbarRequest $request)
    {
        $topbar = $this->topbarRepository->findWithoutFail($id);

        if (empty($topbar)) {
            Flash::error(__('operation.topbars.not_found'));

            return redirect(route('operation.topbars.index'));
        }
        $input                     = $request->all();
        $topbarData                = [];
        $topbarData['name']        = $input['name'];
        $topbarData['title']       = $input['title'];
        $topbarData['description'] = $input['description'];
        $topbarData['css']         = $input['css'];
        // 如果删除原图
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl = $topbar->ui;
            // 根据配置得到根路径
            $rootDir = "";
            if (!$rootDir) {
                $rootDir = config('filesystems.disks.admin.root');
            }
            $fullPath = $rootDir . $imgUrl;
            @unlink($fullPath);
            $topbar->ui = null;
            $topbar->save();
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'css' => 'max:50',
        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.topbar');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $topbarData['ui'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $topbar     = $this->topbarRepository->update($topbarData, $id);
        $topbarArea = $input['topbararea'];

        $datas = [];
        foreach ($topbarArea as $key => $value) {
            $data = [];
            if ($value['_remove_'] != '1') {
                $data['topbar_id'] = $id;
                $data['layout']    = $value['layout'];
                $data['component'] = $value['component'];
                $data['onfocus']   = $value['onfocus'];
                $data['onclick']   = $value['onclick'];
                $data['editable']  = $value['editable'];
                $datas[]           = $data;
            }
        }
        DB::beginTransaction();
        try {
            DB::table('topbar_areas')->where('topbar_id', $id)->delete();
            DB::table('topbar_areas')->insert($datas);
            DB::commit();
        } catch (Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            throw $e;
        }
        Flash::success(__('operation.topbars.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.topbars.index'));
    }

    /**
     * Remove the specified Topbar from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->topbarRepository->batchDelete('id', $id)) {
                DB::table('topbar_areas')->whereIn('topbar_id', $id)->delete();
                return response()->json(['message' => __('operation.topbars.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $topbar = $this->topbarRepository->findWithoutFail($id);

        if (empty($topbar)) {
            Flash::error(__('operation.topbars.not_found'));

            return redirect(route('operation.topbars.index'));
        }

        if ($flag = $this->topbarRepository->delete($id)) {
            DB::table('topbar_areas')->where('topbar_id', $id)->delete();
            return response()->json(['message' => __('operation.topbars.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Topbar::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称');
            $form->text('title', '显示名');
            $form->textarea('description', '描述');
            $form->image('ui', 'UI')->removable();
            $form->text('css', 'css');
            $form->hasMany('topbararea', 'topbar模板布局', function (Form\NestedForm $form) {
                $form->text('layout', '布局名称');
                $form->text('component', '组件名称');
                $form->text('onfocus', 'onfocus');
                $form->text('onclick', 'onclick');
                $form->text('editable', 'editable');

            })->rules("required");
            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Topbar::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('operation.topbars.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('operation.topbars.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('operation.topbars.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('operation.topbars.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('operation.topbars.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('operation.topbars.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('operation.topbars.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('operation.topbars.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('operation.topbars.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('operation.topbars.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '显示名')->sortable();
            $grid->column('description', '描述')->sortable();
            $grid->column('ui', 'UI')->image();
            $grid->column('css', 'css')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }
}
